﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Module_Debug
{
    public partial class SD_write : Form
    {
        frmMain MainForm = null;
        string FileName = "";
        string FileName1 = "";
        private List<string> ImageType;

        CRC16 CRCData = new CRC16();

        public SD_write(frmMain Frm)
        {
            MainForm = Frm;
            InitializeComponent();
        }
        private void SD_write_Load(object sender, EventArgs e)
        {
            string[] s = { ".bmp" };
            this.ImageType = new List<string>(s);
        }

        private void BMP_SEL(object sender, EventArgs e)
        {
            string defaultfilePath = "";
            string path = "";
            if (textBox2.Text != "")
            {
                defaultfilePath = textBox2.Text;
            }
            else
            {
                StreamReader streamReader = new StreamReader("./update/Picaddr.txt", Encoding.Default);
                defaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (defaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = defaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            defaultfilePath = fldb.SelectedPath;
            path = fldb.SelectedPath;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            DirectoryInfo di = new DirectoryInfo(path);
            this.listBox1_BMPFile.Items.Clear();
            this.CreateListItem(di);//递归加载文件夹里的所有图片
            textBox2.Text = path;
            // -------------------------------------------------------------------------
            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Picaddr.txt", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(defaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
        }
        private void CreateListItem(DirectoryInfo di)
        {
            foreach (DirectoryInfo childDi in di.GetDirectories())
            {
                this.CreateListItem(childDi);
            }
            foreach (FileInfo fi in di.GetFiles())
            {
                if (ImageType.Contains(fi.Extension))//找到一个图片(如果用户手贱把一个excel文件后缀改成jpeg没办法)
                {
                    this.listBox1_BMPFile.Items.Add(new MyImages(fi.FullName));
                }
            }
        }

        private void CFG_W(object sender, EventArgs e)
        {
            Int32 m_txlen = 0;
            byte[] TemFileContent = new byte[120 * 1024];
            byte[] File_length = new byte[12];
            Int32 ByteReaded = 0;
            FileStream aFile = new FileStream(textBox1.Text, FileMode.Open);
            //   btnStm32update.Enabled = false;
            //  btnFileSel.Enabled = false;
            //////////////协议制定
            progressBar1.Value = 0;
            label1.Text = "0" + "%";
            File_length[0] = 0x66;
            File_length[1] = 0x01;
            File_length[2] = 0x04;
            File_length[3] = Convert.ToByte(Convert.ToChar((aFile.Length >> 24) % 256));
            File_length[4] = Convert.ToByte(Convert.ToChar((aFile.Length >> 16) % 256));
            File_length[5] = Convert.ToByte(Convert.ToChar((aFile.Length >> 8) % 256));
            File_length[6] = Convert.ToByte(Convert.ToChar((aFile.Length) % 256));
            File_length[7] = 0xff;
            File_length[8] = 0xff;
            File_length[9] = 0;

            CRCData.CalculateCrc16(File_length, out File_length[10], out File_length[11]);
            try
            {
                if (MainForm.comPort.IsOpen == false) MainForm.comPort.Open();
                MainForm.comPort.Write(File_length, 0, 12);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
            Application.DoEvents();
            System.Threading.Thread.Sleep(300);
            ByteReaded = aFile.Read(TemFileContent, 0, 512);
            MainForm.continueflag = 1;
            //   button3.Enabled = false;
            while (MainForm.start_trans_flag != 0x00)
            {

                while (ByteReaded > 0)
                {
                    if (MainForm.continueflag == 1)
                    {
                        MainForm.continueflag = 0;
                        if (MainForm.start_trans_flag == 0x00)
                            break;
                        try
                        {
                            if (MainForm.comPort.IsOpen == false) MainForm.comPort.Open();
                            MainForm.comPort.Write(TemFileContent, 0, ByteReaded);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                            break;
                        }
                        m_txlen += ByteReaded;
                        ByteReaded = aFile.Read(TemFileContent, 0, 512);
                        progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                        label1.Text = progressBar1.Value.ToString() + "%";
                        Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                    }
                }
                MainForm.start_trans_flag = 0x00;
            }

            // button3.Enabled = true;
            aFile.Close();
            //btnStm32update.Enabled = true;
            //btnFileSel.Enabled = true;   
            Application.DoEvents();
            //    MainForm.textBox1.Text += "下方信息栏出现红色闪动后即可关闭升级对话框\r\n";

        }
        private void CFG_SEL(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            string[] arr = new string[12];
            of.Filter = @"cfg文件(*.cfg)|*.cfg|所有文件(*.*)|*.*"; ;
            of.Title = "CFG载入";

            if (of.ShowDialog() == DialogResult.OK)
            {
                FileName = of.FileName;
                textBox1.Text = FileName;
                //  btnStm32update.Enabled = true;
            }
        }

        private void BMP_W(object sender, EventArgs e)
        {
            Int32 m_txlen = 0;
            int i = 0;
            byte[] TemFileContent = new byte[120 * 1024];
            byte[] File_length = new byte[12];
            Int32 ByteReaded = 0;

            for (i = 0; i < listBox1_BMPFile.Items.Count; i++)
            {
                m_txlen = 0;
                progressBar1.Value = 0;
                label1.Text = "0" + "%";
                listBox1_BMPFile.SelectedIndex = i;
                MyImages listPath = (MyImages)listBox1_BMPFile.SelectedItem;

                //FileStream aFile = new FileStream((Fina.Path, FileMode.Open);
                FileStream aFile = new FileStream(listPath.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                System.Threading.Thread.Sleep(200);
                //   btnStm32update.Enabled = false;
                //  btnFileSel.Enabled = false;
                //////////////协议制定
                File_length[0] = 0x66;
                File_length[1] = 0x02;
                File_length[2] = 0x04;
                File_length[3] = Convert.ToByte(Convert.ToChar((aFile.Length >> 24) % 256));
                File_length[4] = Convert.ToByte(Convert.ToChar((aFile.Length >> 16) % 256));
                File_length[5] = Convert.ToByte(Convert.ToChar((aFile.Length >> 8) % 256));
                File_length[6] = Convert.ToByte(Convert.ToChar((aFile.Length) % 256));
                File_length[7] = 0xff;
                File_length[8] = 0xff;
                File_length[9] = (byte)i;
                CRCData.CalculateCrc16(File_length, out File_length[10], out File_length[11]);
                try
                {
                    if (MainForm.comPort.IsOpen == false) MainForm.comPort.Open();
                    MainForm.comPort.Write(File_length, 0, 12);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
                Application.DoEvents();
                System.Threading.Thread.Sleep(300);
                ByteReaded = aFile.Read(TemFileContent, 0, 512);
                MainForm.continueflag = 1;
                //   button3.Enabled = false;
                while (MainForm.start_trans_flag != 0x00)
                {

                    while (ByteReaded > 0)
                    {
                        if (MainForm.continueflag == 1)
                        {
                            MainForm.continueflag = 0;
                            System.Threading.Thread.Sleep(10);
                            if (MainForm.start_trans_flag == 0x00)
                                break;
                            try
                            {
                                if (MainForm.comPort.IsOpen == false) MainForm.comPort.Open();
                                MainForm.comPort.Write(TemFileContent, 0, ByteReaded);
                            }
                            catch
                            {
                                MessageBox.Show("串口有误，请检查", "错误");
                                break;
                            }
                            m_txlen += ByteReaded;
                            ByteReaded = aFile.Read(TemFileContent, 0, 512);
                            progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                            label1.Text = progressBar1.Value.ToString() + "%";
                            Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                        }
                    }
                    MainForm.start_trans_flag = 0x00;
                }
                aFile.Close();
                Application.DoEvents();
                //    MainForm.textBox1.Text += "下方信息栏出现红色闪动后即可关闭升级对话框\r\n";
            }
        }
        public class MyImages
        {
            public MyImages(string p)
            {
                this.Path = p;
            }
            public string Path { get; set; }
            public override string ToString()
            {
                if (Path == null)
                {
                    return null;
                }
                return System.IO.Path.GetFileName(this.Path);
            }
        }
    }
}
